package com.example.lay.io;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by cuilei on 2014/12/8.
 */
public class PreferencesActivity extends Activity {

    private SharedPreferences preferences;
    private SharedPreferences.Editor editor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.acvitity_preferences);
        //只能被本程序读取
        preferences = getSharedPreferences("wscl", MODE_WORLD_READABLE);
        editor = preferences.edit();
        int count = preferences.getInt("count", 0);
        Toast.makeText(this, "程序被使用了" + count + "次", Toast.LENGTH_SHORT).show();
        editor =  preferences.edit().putInt("count",++count);
        editor.commit();
    }

    public void read(View view) {
        String time = preferences.getString("time", null);
        int ranDomNum = preferences.getInt("random", 0);
        String result = time == null ? "您没有写入数据!" : "你上次写入的时间为：" + time + "\n" + "写入随机数为：" + ranDomNum;
        Toast.makeText(this, result, Toast.LENGTH_LONG).show();
    }

    public void write(View view) {
        //写入数据
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日" + ":hh:mm:ss");
        editor.putString("time", sdf.format(new Date()));
        editor.putInt("random", (int) (Math.random() * 100));
        editor.commit();
    }
}
